import {useLoading, useShowToast} from "../../hooks"
import {getFriendCardAPI, likeOrDislikeAPI} from "../../api"
import {BrokenHeartIcon, HeartIcon} from "../../assets/icons"
import React, {useEffect, useRef, useState} from "react"
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Dimensions,
} from "react-native"
import Swiper from "react-native-deck-swiper"
import Svg, {Path} from "react-native-svg"
import {FriendCardParams, FriendCards, FriendsCardItem} from "types/friend"
import {useTHNavigation} from "../../utils/navigation"

const {width} = Dimensions.get("window")
const SIDE_MARGIN = 24
const CARD_WIDTH = width - SIDE_MARGIN * 2
const CARD_HEIGHT = 480

export default function TanHua() {
  const [cards, setCards] = useState<FriendCards>([])
  // 示例静态数据，后续可用 @State 动态替换
  const swiperRef = useRef<Swiper<FriendsCardItem>>(null)
  const [finished, setFinished] = useState(false)
  const showToast = useShowToast()
  const showLoading = useLoading()
  const navigation = useTHNavigation()

  const params: FriendCardParams = {
    page: 1,
    pagesize: 5,
  }
  useEffect(() => {
    getFriendCard()
  }, [])

  const getFriendCard = async () => {
    const close = showLoading() // 打开进度条
    const res = await getFriendCardAPI(params)
    setCards(res)
    close() // 关闭进度条
  }

  const renderCard = (item: FriendsCardItem) => (
    <TouchableOpacity
      onPress={() =>
        navigation.push("Chat", {
          id: item.id,
        })
      }>
      <View style={styles.cardItem}>
        <Image
          source={{
            uri: item?.header.includes("http")
              ? item?.header
              : "http://api-tanhua-harmony.itheima.net" + item?.header,
          }}
          style={styles.avatar}
        />
        <View style={{width: "100%", height: 1, backgroundColor: "#f0f0f0"}} />
        <View style={styles.infoBox}>
          <View style={styles.nameRow}>
            <Text style={styles.name}>{item?.nick_name}</Text>
            <View style={styles.ageBox}>
              <Svg width={18} height={18} viewBox="0 0 24 24" fill="none">
                <Path
                  d="M12 2v2"
                  stroke="#FF5B5B"
                  strokeWidth="2"
                  strokeLinecap="round"
                />
                <Path
                  d="M12 6a7 7 0 100 14 7 7 0 000-14z"
                  stroke="#FF5B5B"
                  strokeWidth="2"
                />
                <Path
                  d="M12 10v3l2 2"
                  stroke="#FF5B5B"
                  strokeWidth="2"
                  strokeLinecap="round"
                />
              </Svg>
              <Text style={styles.age}>{item?.age}</Text>
            </View>
          </View>
          <View style={styles.infoRow}>
            <Text style={styles.infoText}>{item?.marry}</Text>
            <Text style={styles.infoSplit}>|</Text>
            <Text style={styles.infoText}>{item?.xueli}</Text>
          </View>
        </View>
      </View>
    </TouchableOpacity>
  )
  // 左滑不喜欢
  const onSwipedLeft = async (index: number) => {
    if (cards[index]) {
      await likeOrDislikeAPI(cards[index].id, "dislike")
      showToast("不喜欢")
    }
  }
  // 右滑喜欢

  const onSwipedRight = async (index: number) => {
    if (cards[index]) {
      await likeOrDislikeAPI(cards[index].id, "like")
      showToast("喜欢")
    }
  }
  // 不喜欢朋友
  const disLikeFriend = async () => {
    if (!finished) {
      swiperRef.current?.swipeLeft()
    }
  }
  // 喜欢朋友
  const likeFriend = () => {
    if (!finished) {
      swiperRef.current?.swipeRight()
    }
  }
  const onSwipedAll = async () => {
    // 如果还有数据
    setFinished(true)
  }

  return (
    <View style={styles.container}>
      {/* 顶部渐变背景 */}
      <Image
        style={styles.topBackImg}
        source={require("../../res/tan_back.png")}
      />
      {/* 顶部栏 */}
      <View style={styles.topBar}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Image
            source={require("../../res/left.png")}
            style={{width: 24, height: 24}}
          />
        </TouchableOpacity>
        <Text style={styles.topBarTitle}>探花</Text>
        <View style={{width: 24, height: 24}} />
      </View>
      {/* 内容区 */}
      <View style={styles.content}>
        <View style={styles.centerBox}>
          {/* 探花卡片 */}
          <View style={styles.cardWrap}>
            <Swiper
              ref={swiperRef}
              cards={cards}
              renderCard={renderCard}
              cardIndex={0}
              backgroundColor={"transparent"}
              stackSize={3}
              cardVerticalMargin={0}
              cardHorizontalMargin={0}
              disableBottomSwipe
              disableTopSwipe
              onSwipedLeft={onSwipedLeft}
              onSwipedRight={onSwipedRight}
              onSwipedAll={onSwipedAll}
              cardStyle={{
                width: CARD_WIDTH,
                alignSelf: "center",
              }}
              containerStyle={{
                width: width,
                alignItems: "center",
                justifyContent: "center",
                flex: 1,
                flexDirection: "row",
              }}
            />
          </View>
          {/* 底部操作按钮 */}
          <View style={styles.btnRow}>
            <TouchableOpacity style={styles.btnCircle} onPress={disLikeFriend}>
              <BrokenHeartIcon size={36} color="#B0B0B0" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={likeFriend}
              style={[styles.btnCircle, styles.btnActive]}>
              <HeartIcon size={36} color="#fff" />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F2FAFF",
  },
  topBackImg: {
    position: "absolute",
    width: "100%",
    height: 480,
    top: 0,
    left: 0,
    zIndex: 0,
  },
  topBar: {
    height: 56,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    marginTop: 30,
    zIndex: 1,
  },
  topBarTitle: {
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
    textAlign: "center",
  },
  content: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 36,
    paddingBottom: 40,
  },

  infoBox: {
    width: "100%",
    alignItems: "center",
    paddingVertical: 16,
    backgroundColor: "#fff",
    flex: 1,
    borderBottomLeftRadius: 24,
    borderBottomRightRadius: 24,
  },
  nameRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 6,
  },
  name: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#333",
    marginRight: 8,
  },
  ageBox: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "transparent",
  },
  age: {
    fontSize: 16,
    color: "#FF5B5B",
    marginLeft: 2,
  },
  infoRow: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 6,
  },
  infoText: {
    fontSize: 15,
    color: "#B0B0B0",
    marginHorizontal: 2,
  },
  infoSplit: {
    color: "#E0E0E0",
    marginHorizontal: 8,
    fontSize: 15,
  },
  btnRow: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
    marginTop: 32,
  },
  btnCircle: {
    width: 76,
    height: 76,
    borderRadius: 38,
    backgroundColor: "#fff",
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: 28,
    shadowColor: "#000",
    shadowOffset: {width: 0, height: 6},
    shadowOpacity: 0.1,
    shadowRadius: 12,
    elevation: 6,
  },
  btnActive: {
    backgroundColor: "#FF5B5B",
    shadowColor: "#FF5B5B",
    shadowOpacity: 0.18,
  },
  centerBox: {
    alignItems: "center",
    width: width,
    position: "relative",
  },
  cardWrap: {
    width: width,
    height: CARD_HEIGHT,
    alignItems: "center",
    justifyContent: "flex-end",
    marginLeft: 40,
  },
  cardItem: {
    width: CARD_WIDTH,
    height: CARD_HEIGHT,
    borderRadius: 24,
    overflow: "hidden",
    backgroundColor: "#fff",
    alignItems: "center",
  },
  avatar: {
    width: "100%",
    height: 340,
    resizeMode: "cover",
  },
})
